package com.example.myapplication.fragment;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.myapplication.MyConstant;
import com.example.myapplication.R;
import com.example.myapplication.databinding.FragmentQuestionBinding;
import com.example.myapplication.utils.SpUtils;
import com.example.myapplication.viewmodel.MyViewModel;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

public class QuestionFragment extends Fragment {
    private StringBuilder sb;
    private FragmentQuestionBinding binding;
    private MyViewModel myViewModel;
    private int timeCount;
    private Handler mHandler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        myViewModel = ViewModelProviders.of(requireActivity(), new SavedStateViewModelFactory(requireActivity().getApplication(),
                requireActivity())).get(MyViewModel.class);

        myViewModel.generator();
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_question, container, false);
        binding.setData(myViewModel);
        binding.setLifecycleOwner(requireActivity());

        sb = new StringBuilder();
        View.OnClickListener listenerAA = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.button0:
                        sb.append("0");
                        break;
                    case R.id.button1:
                        sb.append("1");
                        break;
                    case R.id.button2:
                        sb.append("2");
                        break;
                    case R.id.button3:
                        sb.append("3");
                        break;
                    case R.id.button4:
                        sb.append("4");
                        break;
                    case R.id.button5:
                        sb.append("5");
                        break;
                    case R.id.button6:
                        sb.append("6");
                        break;
                    case R.id.button7:
                        sb.append("7");
                        break;
                    case R.id.button8:
                        sb.append("8");
                        break;
                    case R.id.button9:
                        sb.append("9");
                        break;
                    case R.id.button_clear:
                        sb.setLength(0);
                        break;
                    case R.id.button_submit:

                        break;
                }
                if (sb.length() == 0) {
                    binding.tvAnswer.setText("请输入答案");
                } else {
                    binding.tvAnswer.setText(sb);
                }
                MediaPlayer.create(getContext(),R.raw.deng).start();
            }
        };
        binding.button0.setOnClickListener(listenerAA);
        binding.button1.setOnClickListener(listenerAA);
        binding.button2.setOnClickListener(listenerAA);
        binding.button3.setOnClickListener(listenerAA);
        binding.button4.setOnClickListener(listenerAA);
        binding.button5.setOnClickListener(listenerAA);
        binding.button6.setOnClickListener(listenerAA);
        binding.button7.setOnClickListener(listenerAA);
        binding.button8.setOnClickListener(listenerAA);
        binding.button9.setOnClickListener(listenerAA);
        binding.button0.setOnClickListener(listenerAA);
        binding.buttonClear.setOnClickListener(listenerAA);
//        binding.buttonSubmit.setOnClickListener(listenerAA);
        binding.buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("请输入答案".equals(binding.tvAnswer.getText()) || "回答正确，请继续答题！".equals(binding.tvAnswer.getText())) {
                    return;
                }

                if (sb.toString().equals(myViewModel.getAnwser().getValue().toString())) {
                    //回答正确
                    myViewModel.anwserCorrect();
                    MediaPlayer.create(getContext(),R.raw.you_are_grate).start();
                    Log.d("fenshu", "" + myViewModel.getCurrentScore().getValue());
                    //做对 10 题，挑战成功
                    int questionNum = SpUtils.getInt(getContext(), MyConstant.QUESTION_NUM, 10);
                    if (myViewModel.getCurrentScore().getValue() == questionNum) {

                        Bundle bundle = new Bundle();
                        if (SpUtils.getBoolean(getContext(), MyConstant.TIME_COUNT, true)) {
                            mHandler.removeCallbacksAndMessages(null);
                            bundle.putInt("time_count", timeCount);
                        }
                        NavController navController = Navigation.findNavController(view);
                        navController.navigate(R.id.action_questionFragment_to_winFragment2, bundle);
                        myViewModel.win_flag = false;
                        myViewModel.saveHighestScore();
                    }

                    sb.setLength(0);
                    binding.tvAnswer.setText("回答正确，请继续答题！");
                    binding.tvNum.setText("第 " + (myViewModel.getCurrentScore().getValue() + 1) + " 题");
                } else {
                    //回答失败
                    if (SpUtils.getBoolean(getContext(), MyConstant.TIME_COUNT, true)) {
                        mHandler.removeCallbacksAndMessages(null);
                    }
                    NavController navController = Navigation.findNavController(view);
                    Bundle bundle = new Bundle();
                    String wrongAnswer = myViewModel.getLeftNum().getValue() + " " + myViewModel.getOperator().getValue() + " "
                            + myViewModel.getRightNum().getValue() + " = " + sb;

                    String trueAnswer = myViewModel.getLeftNum().getValue() + " " + myViewModel.getOperator().getValue() + " "
                            + myViewModel.getRightNum().getValue() + " = " + myViewModel.getAnwser().getValue();
                    bundle.putString("wrongAnswer", wrongAnswer);
                    bundle.putString("trueAnswer", trueAnswer);
                    navController.navigate(R.id.action_questionFragment_to_loseFragment2, bundle);
//                            if (myViewModel.win_flag) {
//                                navController.navigate(R.id.action_questionFragment_to_winFragment2);
//                                myViewModel.win_flag = false;
//                                myViewModel.saveHighestScore();
//                            } else {
//                                Bundle bundle = new Bundle();
//                                bundle.putInt("key",666);
//                                navController.navigate(R.id.action_questionFragment_to_loseFragment2,bundle);
//                            }

                }
            }
        });


        return binding.getRoot();
    }

    private void timeCount() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                timeCount++;
                binding.tvTimeCount.setText("当前用时：" + timeCount);
                mHandler.postDelayed(this, 1000);
            }
        }, 1000);
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.tvTimeCount.setVisibility(View.VISIBLE);
        if (SpUtils.getBoolean(getContext(), MyConstant.TIME_COUNT, true)) {
            if (mHandler == null) {
                mHandler = new Handler();
                timeCount();
            }
        } else {
            binding.tvTimeCount.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null)
            mHandler.removeCallbacksAndMessages(null);
    }

}
